package com.huitone.smspfm.socket.core.verificate;

import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.socket.core.verificate.Validator;
import com.huitone.smspfm.socket.model.AccountInfo;
import com.huitone.smspfm.socket.protocol.sgip.constant.ErrorCode;
import com.huitone.smspfm.socket.protocol.sgip.message.msgbody.Bind;

public class SimpleUserValidator implements Validator {
	
	private static final Logger logger = LogManager.getLogger(SimpleUserValidator.class);
	
	private String username = null;
	private String password = null;
	
	public SimpleUserValidator(String username, String password) {
		this.username = username;
		this.password = Base64.encodeBase64String(StringUtils.toString(password).getBytes());
	}

	@Override
	public Result verificate(Bind bind,String ip){
		return verificate(bind);
	}
	
	@Override
	public Result verificate(Bind bind) {
		
		Result result = new Result();
		
		if (bind != null) {
			
			// 这是一条Bind请求
			String srvNode = bind.getSrvNode();
			String username = bind.getLoginName();
			String password = bind.getLoginPassword();
			
			AccountInfo accountInfo = check(srvNode, username, password);
			
			if (accountInfo != null) {
				result.setAccountInfo(accountInfo);
				result.setErrorCode(ErrorCode.CODE0);
				result.setAccept(true);
			} else {
				result.setErrorCode(ErrorCode.CODE_17);
				result.setAccept(false);
			}
		}
		
		return result;
	}
	
	public AccountInfo check(String srvNode, String username, String password) {
		
		AccountInfo accountInfo = null;
		
		if (StringUtils.equals(this.username, username) 
				&& StringUtils.equals(this.password, password)) {
			accountInfo = new AccountInfo();
			accountInfo.setSrvNode(srvNode);
			accountInfo.setLoginName(username);
			accountInfo.setLoginPassword(password);
			accountInfo.setLogin(true);
			
			logger.info("校验成功");
			
		} else {
			logger.warn("用户名帐号密码校验失败,请求登录的帐号:"+username + ",密码:"+password);
		}
		
		return accountInfo;
	}

}
